package sonic.game;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

import sonic.game.tile.Tile;

/**
 * Game Panel
 * 
 * Draws the screen based on the game state
 * 
 * @author Richard Greenlees
 *
 */


public class GamePanel extends JPanel
{
	private static final long serialVersionUID = 1L;

	
	public Game currentGame;
	
	public GamePanel()
	{
		this.addKeyListener(new AL());
		this.setFocusable(true);		
	}
	
	/** Cycle through the tiles and let the relevant ones do their own painting */
	public void paint(Graphics g)
	{
		if(Game.currentMap != null)
		{
			g.drawImage(Game.currentMap.backgroundImage, 0, 0, null);
			for (Tile a : Game.currentMap.relevantTiles)
			{
				if (a.isRelevant())
				{
					a.paint(g);
				}
			}
			// Paint the player separately
			Game.player.paint(g);
			g.drawString(""+Game.player.rings, 5, 15);
		}
	}
	
	/** Private key listener class for the Game Panel */
	private class AL implements KeyListener
	{
		public void keyReleased(KeyEvent e)
		{
			int key = e.getKeyCode();
			
			if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_LEFT)
			{
				Game.player.directionHeld = 0;
			}
			else if (key == KeyEvent.VK_DOWN)
			{
				Game.player.endDuck();
			}

		}
		
		/** Register player input and pass the appropriate action to the Sonic class for handling */
		public void keyPressed(KeyEvent e)
		{
			int key = e.getKeyCode();
			if (key == KeyEvent.VK_RIGHT)
			{
				Game.player.directionHeld = 1;
			}
			else if (key == KeyEvent.VK_LEFT)
			{
				Game.player.directionHeld = -1;
			}
			else if (key == KeyEvent.VK_SPACE)
			{
				Game.player.doJump();
			}
			else if (key == KeyEvent.VK_DOWN)
			{
				Game.player.beginDuck();
			}
		}

		public void keyTyped(KeyEvent arg0)
		{
			// Mandatory method from abstract super class. Not needed.
		}	
	}
}
